<!DOCTYPE html>
<html lang="zh" dir="ltr" class="client-nojs">
<head>
<title>联合体声明</title>
<meta charset="UTF-8">
<meta name="generator" content="MediaWiki 1.21.2">
<link rel="shortcut icon" href="../../../common/favicon.ico">
<link rel="stylesheet" href="../../../common/ext.css">
<meta name="ResourceLoaderDynamicStyles" content="">
<link rel="stylesheet" href="../../../common/site_modules.css">
<style>a:lang(ar),a:lang(ckb),a:lang(fa),a:lang(kk-arab),a:lang(mzn),a:lang(ps),a:lang(ur){text-decoration:none}#toc{display:none}.editsection{display:none}
/* cache key: mwiki1-mwiki_zh_:resourceloader:filter:minify-css:7:15cea3ec788a65b5187d4018eed543bf */</style>

<script src="../../../common/startup_scripts.js"></script>
<script>if(window.mw){
mw.config.set({"wgCanonicalNamespace":"","wgCanonicalSpecialPageName":false,"wgNamespaceNumber":0,"wgPageName":"cpp/language/union","wgTitle":"cpp/language/union","wgCurRevisionId":60229,"wgArticleId":2764,"wgIsArticle":true,"wgAction":"view","wgUserName":null,"wgUserGroups":["*"],"wgCategories":["Pages with unreviewed CWG DR marker"],"wgBreakFrames":false,"wgPageContentLanguage":"zh","wgSeparatorTransformTable":["",""],"wgDigitTransformTable":["",""],"wgDefaultDateFormat":"zh","wgMonthNames":["","1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"wgMonthNamesShort":["","1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"wgRelevantPageName":"cpp/language/union","wgUserVariant":"zh","wgRestrictionEdit":[],"wgRestrictionMove":[]});
}</script><script>if(window.mw){
mw.loader.implement("user.options",function(){mw.user.options.set({"ccmeonemails":0,"cols":80,"date":"default","diffonly":0,"disablemail":0,"disablesuggest":0,"editfont":"default","editondblclick":0,"editsection":0,"editsectiononrightclick":0,"enotifminoredits":0,"enotifrevealaddr":0,"enotifusertalkpages":1,"enotifwatchlistpages":0,"extendwatchlist":0,"externaldiff":0,"externaleditor":0,"fancysig":0,"forceeditsummary":0,"gender":"unknown","hideminor":0,"hidepatrolled":0,"imagesize":2,"justify":0,"math":1,"minordefault":0,"newpageshidepatrolled":0,"nocache":0,"noconvertlink":0,"norollbackdiff":0,"numberheadings":0,"previewonfirst":0,"previewontop":1,"quickbar":5,"rcdays":7,"rclimit":50,"rememberpassword":0,"rows":25,"searchlimit":20,"showhiddencats":0,"showjumplinks":1,"shownumberswatching":1,"showtoc":0,"showtoolbar":1,"skin":"cppreference2","stubthreshold":0,"thumbsize":2,"underline":2,"uselivepreview":0,"usenewrc":0,"watchcreations":0,"watchdefault":0,"watchdeletion":0,
"watchlistdays":3,"watchlisthideanons":0,"watchlisthidebots":0,"watchlisthideliu":0,"watchlisthideminor":0,"watchlisthideown":0,"watchlisthidepatrolled":0,"watchmoves":0,"wllimit":250,"variant":"zh","language":"zh","searchNs0":true,"searchNs1":false,"searchNs2":false,"searchNs3":false,"searchNs4":false,"searchNs5":false,"searchNs6":false,"searchNs7":false,"searchNs8":false,"searchNs9":false,"searchNs10":false,"searchNs11":false,"searchNs12":false,"searchNs13":false,"searchNs14":false,"searchNs15":false,"gadget-MathJax":1,"gadget-ColiruCompiler":1});;},{},{});mw.loader.implement("user.tokens",function(){mw.user.tokens.set({"editToken":"+\\","patrolToken":false,"watchToken":false});;},{},{});
/* cache key: mwiki1-mwiki_zh_:resourceloader:filter:minify-js:7:258d7cd6aa9aa67dee25e01fb6a9e505 */
}</script>
<script>if(window.mw){
mw.loader.load(["mediawiki.page.startup","mediawiki.legacy.wikibits","mediawiki.legacy.ajax"]);
}</script>
<style type="text/css">/*<![CDATA[*/
.source-cpp {line-height: normal;}
.source-cpp li, .source-cpp pre {
	line-height: normal; border: 0px none white;
}
/**
 * GeSHi Dynamically Generated Stylesheet
 * --------------------------------------
 * Dynamically generated stylesheet for cpp
 * CSS class: source-cpp, CSS id: 
 * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann
 * (http://qbnz.com/highlighter/ and http://geshi.org/)
 * --------------------------------------
 */
.cpp.source-cpp .de1, .cpp.source-cpp .de2 {font: normal normal 1em/1.2em monospace; margin:0; padding:0; background:none; vertical-align:top;}
.cpp.source-cpp  {font-family:monospace;}
.cpp.source-cpp .imp {font-weight: bold; color: red;}
.cpp.source-cpp li, .cpp.source-cpp .li1 {font-weight: normal; vertical-align:top;}
.cpp.source-cpp .ln {width:1px;text-align:right;margin:0;padding:0 2px;vertical-align:top;}
.cpp.source-cpp .li2 {font-weight: bold; vertical-align:top;}
.cpp.source-cpp .kw1 {color: #0000dd;}
.cpp.source-cpp .kw2 {color: #0000ff;}
.cpp.source-cpp .kw3 {color: #0000dd;}
.cpp.source-cpp .kw4 {color: #0000ff;}
.cpp.source-cpp .co1 {color: #909090;}
.cpp.source-cpp .co2 {color: #339900;}
.cpp.source-cpp .coMULTI {color: #ff0000; font-style: italic;}
.cpp.source-cpp .es0 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es1 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es2 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es3 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es4 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es5 {color: #008000; font-weight: bold;}
.cpp.source-cpp .br0 {color: #008000;}
.cpp.source-cpp .sy0 {color: #008000;}
.cpp.source-cpp .sy1 {color: #000080;}
.cpp.source-cpp .sy2 {color: #000040;}
.cpp.source-cpp .sy3 {color: #000040;}
.cpp.source-cpp .sy4 {color: #008080;}
.cpp.source-cpp .st0 {color: #008000;}
.cpp.source-cpp .nu0 {color: #000080;}
.cpp.source-cpp .nu6 {color: #000080;}
.cpp.source-cpp .nu8 {color: #000080;}
.cpp.source-cpp .nu12 {color: #000080;}
.cpp.source-cpp .nu16 {color:#000080;}
.cpp.source-cpp .nu17 {color:#000080;}
.cpp.source-cpp .nu18 {color:#000080;}
.cpp.source-cpp .nu19 {color:#000080;}
.cpp.source-cpp .ln-xtra, .cpp.source-cpp li.ln-xtra, .cpp.source-cpp div.ln-xtra {background-color: #ffc;}
.cpp.source-cpp span.xtra { display:block; }

/*]]>*/
</style><style type="text/css">/*<![CDATA[*/
.source-text {line-height: normal;}
.source-text li, .source-text pre {
	line-height: normal; border: 0px none white;
}
/**
 * GeSHi Dynamically Generated Stylesheet
 * --------------------------------------
 * Dynamically generated stylesheet for text
 * CSS class: source-text, CSS id: 
 * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann
 * (http://qbnz.com/highlighter/ and http://geshi.org/)
 * --------------------------------------
 */
.text.source-text .de1, .text.source-text .de2 {font: normal normal 1em/1.2em monospace; margin:0; padding:0; background:none; vertical-align:top;}
.text.source-text  {font-family:monospace;}
.text.source-text .imp {font-weight: bold; color: red;}
.text.source-text li, .text.source-text .li1 {font-weight: normal; vertical-align:top;}
.text.source-text .ln {width:1px;text-align:right;margin:0;padding:0 2px;vertical-align:top;}
.text.source-text .li2 {font-weight: bold; vertical-align:top;}
.text.source-text .ln-xtra, .text.source-text li.ln-xtra, .text.source-text div.ln-xtra {background-color: #ffc;}
.text.source-text span.xtra { display:block; }

/*]]>*/
</style><!--[if lt IE 7]><style type="text/css">body{behavior:url("/mwiki/skins/cppreference2/csshover.min.htc")}</style><![endif]--></head>
<body class="mediawiki ltr sitedir-ltr ns-0 ns-subject page-cpp_language_union skin-cppreference2 action-view cpp-navbar">
        <!-- header -->
        <!-- /header -->
        <!-- content -->
<div id="cpp-content-base">
            <div id="content">
                <a id="top"></a>
                <div id="mw-js-message" style="display:none;"></div>
                                <!-- firstHeading -->
<h1 id="firstHeading" class="firstHeading">联合体声明</h1>
                <!-- /firstHeading -->
                <!-- bodyContent -->
                <div id="bodyContent">
                                        <!-- tagline -->
                    <div id="siteSub">来自cppreference.com</div>
                    <!-- /tagline -->
                                        <!-- subtitle -->
                    <div id="contentSub"><span class="subpages">&lt; <a href="../../cpp.html" title="cpp">cpp</a>‎ | <a href="../language.html" title="cpp/language">language</a></span></div>
                    <!-- /subtitle -->
                                                            <!-- bodycontent -->
                    <div id="mw-content-text" lang="zh" dir="ltr" class="mw-content-ltr"><div class="t-navbar" style=""><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="../../cpp.html" title="cpp"> C++</a><div class="t-navbar-menu"><div><div><table class="t-nv-begin" cellpadding="0" style="line-height:1.1em;">
<tr class="t-nv"><td colspan="5"> <a href="../language.html" title="cpp/language">语言</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../header.html" title="cpp/header">标准库头文件</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../freestanding.html" title="cpp/freestanding"> 自立与有宿主实现</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../named_req.html" title="cpp/named req">具名要求</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../utility.html#.E8.AF.AD.E8.A8.80.E6.94.AF.E6.8C.81" title="cpp/utility">语言支持库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../concepts.html" title="cpp/concepts">概念库</a> <span class="t-mark-rev t-since-cxx20">(C++20)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../error.html" title="cpp/error">诊断库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../utility.html" title="cpp/utility">工具库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../string.html" title="cpp/string">字符串库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="https://zh.cppreference.com/w/cpp/container" title="cpp/container">容器库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../iterator.html" title="cpp/iterator">迭代器库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../ranges.html" title="cpp/ranges"> 范围库</a> <span class="t-mark-rev t-since-cxx20">(C++20)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../algorithm.html" title="cpp/algorithm">算法库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../numeric.html" title="cpp/numeric">数值库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../io.html" title="cpp/io">输入/输出库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../locale.html" title="cpp/locale">本地化库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../regex.html" title="cpp/regex">正则表达式库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../atomic.html" title="cpp/atomic">原子操作库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../thread.html" title="cpp/thread">线程支持库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../filesystem.html" title="cpp/filesystem">文件系统库</a> <span class="t-mark-rev t-since-cxx17">(C++17)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../experimental.html" title="cpp/experimental">技术规范</a> </td></tr>
</table></div><div></div></div></div></div><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="../language.html" title="cpp/language">C++ 语言</a></div><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="classes.html" title="cpp/language/classes">类</a><div class="t-navbar-menu"><div><div style="display:inline-block">
<div><table class="t-nv-begin" cellpadding="0" style="">
<tr class="t-nv-h2"><td colspan="5">概述</td></tr>
<tr class="t-nv"><td colspan="5"> <a href="classes.html" title="cpp/language/classes">综述</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="class.html" title="cpp/language/class"><code>class</code>/<code>struct</code> 类型</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <strong class="selflink"><code>union</code> 类型</strong> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="injected-class-name.html" title="cpp/language/injected-class-name">注入类名</a> </td></tr>
<tr class="t-nv-h2"><td colspan="5">成员</td></tr>
<tr class="t-nv"><td colspan="5"> <a href="data_members.html" title="cpp/language/data members">数据成员</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="static.html" title="cpp/language/static">静态成员</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="this.html" title="cpp/language/this"><code>this</code> 指针</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="nested_classes.html" title="cpp/language/nested types">嵌套类</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="member_template.html" title="cpp/language/member template">成员模板</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="bit_field.html" title="cpp/language/bit field">位域</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="using_declaration.html" title="cpp/language/using declaration"><code>using</code> 声明</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="member_functions.html" title="cpp/language/member functions">成员函数</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="access.html" title="cpp/language/access">成员访问指定符</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="constructor.html" title="cpp/language/initializer list">构造函数与成员初始化器列表</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="data_members.html#.E6.88.90.E5.91.98.E5.88.9D.E5.A7.8B.E5.8C.96" title="cpp/language/data members">默认成员初始化器</a><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="friend.html" title="cpp/language/friend"><code>friend</code> 指定符</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="explicit.html" title="cpp/language/explicit"><code>explicit</code> 指定符</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="converting_constructor.html" title="cpp/language/converting constructor">转换构造函数</a></td></tr>
<tr class="t-nv-h2"><td colspan="5">特殊成员函数</td></tr>
<tr class="t-nv"><td colspan="5"> <a href="default_constructor.html" title="cpp/language/default constructor">默认构造函数</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="copy_constructor.html" title="cpp/language/copy constructor">复制构造函数</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="move_constructor.html" title="cpp/language/move constructor">移动构造函数</a><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="copy_assignment.html" title="cpp/language/copy assignment">复制赋值运算符</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="move_assignment.html" title="cpp/language/move assignment">移动赋值运算符</a><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="destructor.html" title="cpp/language/destructor">析构函数</a></td></tr>
<tr class="t-nv-h2"><td colspan="5">继承</td></tr>
<tr class="t-nv"><td colspan="5"> <a href="derived_class.html" title="cpp/language/derived class">基与派生类</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="ebo.html" title="cpp/language/ebo">空基类优化</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="virtual.html" title="cpp/language/virtual">虚成员函数</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="abstract_class.html" title="cpp/language/abstract class">纯虚函数与抽象类</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="override.html" title="cpp/language/override"><tt>override</tt></a><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="final.html" title="cpp/language/final"><tt>final</tt></a><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
</table></div>
</div><div></div></div></div></div><div class="t-navbar-sep"> </div></div>
<p>联合体是特殊的类类型，它在一个时刻只能保有其一个非静态<a href="data_members.html" title="cpp/language/data members">数据成员</a>。
</p><p>联合体声明的类说明符与<a href="class.html" title="cpp/language/class">类或结构体</a>的声明相似：
</p>
<table class="t-sdsc-begin">

<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr>
<tr class="t-sdsc">
<td class="t-sdsc-nopad"> <code><b>union</b></code> <span class="t-spar">attr</span> <span class="t-spar">类头名</span> <code><b>{ </b></code> <span class="t-spar">成员说明</span> <code><b>} </b></code>
</td>
<td class="t-sdsc-nopad">
</td>
<td class="t-sdsc-nopad">
</td></tr>



<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr></table>
<table class="t-par-begin">


<tr class="t-par">
<td>  <span class="t-spar">attr</span><span class="t-mark-rev t-since-cxx11">(C++11)</span>
</td>
<td> -
</td>
<td>  任何数量<a href="attributes.html" title="cpp/language/attributes">属性</a>的可选序列
</td></tr>
<tr class="t-par">
<td>  <span class="t-spar">类头名</span>
</td>
<td> -
</td>
<td>  被定义的联合体的名字。可选地前附 <span class="t-spar">嵌套名说明符</span>（名字与作用域解析运算符的序列，以作用域解析运算符结尾）。可忽略名字，该情况下联合体为<i>无名</i>
</td></tr>
<tr class="t-par">
<td>  <span class="t-spar">成员说明</span>
</td>
<td> -
</td>
<td>  访问说明符、成员对象和成员函数的声明与定义的列表。
</td></tr></table>
<p>联合体可拥有成员函数（包含构造函数和析构函数），但不能有虚函数。
</p><p>联合体不能有基类且不能用作基类。
</p><p>联合体不能拥有引用类型的非静态数据成员。
</p>
 <table class="t-rev-begin">
<tr class="t-rev t-until-cxx11"><td>
<p>联合体不能含有带非平凡特殊成员函数（<a href="copy_constructor.html" title="cpp/language/copy constructor">复制构造函数</a>、<a href="copy_assignment.html" title="cpp/language/copy assignment">复制赋值</a>运算符或<a href="destructor.html" title="cpp/language/destructor">析构函数</a>）的非静态数据成员。
</p>
</td>
<td><span class="t-mark-rev t-until-cxx11">(C++11 前)</span></td></tr>
<tr class="t-rev t-since-cxx11"><td>
<p>若联合体含有带非平凡特殊成员函数（<a href="copy_constructor.html" title="cpp/language/copy constructor">复制</a>/<a href="move_constructor.html" title="cpp/language/move constructor">移动</a>构造函数，<a href="copy_assignment.html" title="cpp/language/copy assignment">复制</a>/<a href="move_assignment.html" title="cpp/language/move assignment">移动</a>赋值，或<a href="destructor.html" title="cpp/language/destructor">析构函数</a>）的非静态数据成员，则联合体中的该函数默认被弃置，且需要程序员显式定义它。
</p><p>若联合体含有带非平凡<a href="default_constructor.html" title="cpp/language/default constructor">默认构造函数</a>的非静态数据成员，则该联合体的默认构造函数默认被弃置，除非联合体的<a href="union.html#.E8.81.94.E5.90.88.E4.BD.93.E5.BC.8F.E7.9A.84.E7.B1.BB">变体成员</a>拥有一个默认成员初始化器。
</p><p>至多一个<a href="union.html#.E8.81.94.E5.90.88.E4.BD.93.E5.BC.8F.E7.9A.84.E7.B1.BB">变体成员</a>可以拥有<a href="data_members.html#.E6.88.90.E5.91.98.E5.88.9D.E5.A7.8B.E5.8C.96" title="cpp/language/data members">默认成员初始化器</a>。
</p>
</td>
<td><span class="t-mark-rev t-since-cxx11">(C++11 起)</span></td></tr>
</table>
<p>正如<a href="classes.html" title="cpp/language/classes">结构体的</a>声明中一般，联合体的默认成员访问是 <a href="access.html" title="cpp/language/access">public</a>。
</p>
<h3><span class="mw-headline" id=".E8.A7.A3.E9.87.8A">解释</span></h3>
<p>联合体的大小仅足以保有其最大的数据成员。其他数据成员分配于该最大成员的一部分相同的字节。分配的细节是实现定义的，且从并非最近写入的联合体成员进行读取是未定义行为。许多编译器作为非标准语言扩展，实现读取联合体的不活跃成员的能力。
</p>
<div class="t-example"><div class="t-example-live-link"><div class="coliru-btn coliru-btn-run-init">运行此代码</div></div>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="co2">#include &lt;iostream&gt;</span>
<span class="co2">#include &lt;cstdint&gt;</span>
<span class="kw1">union</span> S
<span class="br0">{</span>
    <a href="../types/integer.html"><span class="kw108">std::<span class="me2">int32_t</span></span></a> n<span class="sy4">;</span>     <span class="co1">// 占用 4 字节</span>
    <a href="../types/integer.html"><span class="kw121">std::<span class="me2">uint16_t</span></span></a> s<span class="br0">[</span><span class="nu0">2</span><span class="br0">]</span><span class="sy4">;</span> <span class="co1">// 占用 4 字节</span>
    <a href="../types/integer.html"><span class="kw120">std::<span class="me2">uint8_t</span></span></a> c<span class="sy4">;</span>     <span class="co1">// 占用 1 字节</span>
<span class="br0">}</span><span class="sy4">;</span>                      <span class="co1">// 整个联合体占用 4 字节</span>
 
<span class="kw4">int</span> main<span class="br0">(</span><span class="br0">)</span>
<span class="br0">{</span>
    S s <span class="sy1">=</span> <span class="br0">{</span><span class="nu12">0x12345678</span><span class="br0">}</span><span class="sy4">;</span> <span class="co1">// 初始化首个成员，s.n 现在是活跃成员</span>
    <span class="co1">// 于此点，从 s.s 或 s.c 读取是未定义行为</span>
    <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <a href="../io/manip/hex.html"><span class="kw1782">std::<span class="me2">hex</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">"s.n = "</span> <span class="sy1">&lt;&lt;</span> s.<span class="me1">n</span> <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span>
    s.<span class="me1">s</span><span class="br0">[</span><span class="nu0">0</span><span class="br0">]</span> <span class="sy1">=</span> <span class="nu12">0x0011</span><span class="sy4">;</span> <span class="co1">// s.s 现在是活跃成员</span>
    <span class="co1">// 在此点，从 n 或 c 读取是 UB 但大多数编译器都对其有定义</span>
    <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">"s.c is now "</span> <span class="sy1">&lt;&lt;</span> <span class="sy2">+</span>s.<span class="me1">c</span> <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span> <span class="co1">// 11 或 00，取决于平台</span>
              <span class="sy1">&lt;&lt;</span> <span class="st0">"s.n is now "</span> <span class="sy1">&lt;&lt;</span> s.<span class="me1">n</span> <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span> <span class="co1">// 12340011 或 00115678</span>
<span class="br0">}</span></pre></div></div>
<p>可能的输出：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="text source-text"><pre class="de1">s.n = 12345678
s.c is now 0
s.n is now 115678</pre></div></div> 
</div>
<p>各个成员都如同它是类的仅有成员一样进行分配。
</p>
 <table class="t-rev-begin">
<tr class="t-rev t-since-cxx11"><td>
<p>若联合体的成员是拥有用户定义的构造函数和析构函数的类，则为了切换其活跃成员，通常需要显式析构函数和布置 new：
</p>
<div class="t-example"><div class="t-example-live-link"><div class="coliru-btn coliru-btn-run-init">运行此代码</div></div>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="co2">#include &lt;iostream&gt;</span>
<span class="co2">#include &lt;string&gt;</span>
<span class="co2">#include &lt;vector&gt;</span>
 
<span class="kw1">union</span> S
<span class="br0">{</span>
    <a href="../string/basic_string.html"><span class="kw1230">std::<span class="me2">string</span></span></a> str<span class="sy4">;</span>
    <a href="../container/vector.html"><span class="kw1269">std::<span class="me2">vector</span></span></a><span class="sy1">&lt;</span><span class="kw4">int</span><span class="sy1">&gt;</span> vec<span class="sy4">;</span>
    ~S<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span><span class="br0">}</span> <span class="co1">// 需要知道哪个成员活跃，仅在联合体式的类中可行</span>
<span class="br0">}</span><span class="sy4">;</span>          <span class="co1">// 整个联合体占有 max(sizeof(string), sizeof(vector&lt;int&gt;)) 的内存</span>
 
<span class="kw4">int</span> main<span class="br0">(</span><span class="br0">)</span>
<span class="br0">{</span>
    S s <span class="sy1">=</span> <span class="br0">{</span><span class="st0">"Hello, world"</span><span class="br0">}</span><span class="sy4">;</span>
    <span class="co1">// 在此点，从 s.vec 读取是未定义行为</span>
    <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">"s.str = "</span> <span class="sy1">&lt;&lt;</span> s.<span class="me1">str</span> <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span>
    s.<span class="me1">str</span>.~basic_string<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span>
    new <span class="br0">(</span><span class="sy3">&amp;</span>s.<span class="me1">vec</span><span class="br0">)</span> <a href="../container/vector.html"><span class="kw1269">std::<span class="me2">vector</span></span></a><span class="sy1">&lt;</span><span class="kw4">int</span><span class="sy1">&gt;</span><span class="sy4">;</span>
    <span class="co1">// 现在，s.vec 是联合体的活跃成员</span>
    s.<span class="me1">vec</span>.<span class="me1">push_back</span><span class="br0">(</span><span class="nu0">10</span><span class="br0">)</span><span class="sy4">;</span>
    <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> s.<span class="me1">vec</span>.<span class="me1">size</span><span class="br0">(</span><span class="br0">)</span> <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span>
    s.<span class="me1">vec</span>.~vector<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span>
<span class="br0">}</span></pre></div></div>
<p>输出：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="text source-text"><pre class="de1">s.str = Hello, world
1</pre></div></div> 
</div>
</td>
<td><span class="t-mark-rev t-since-cxx11">(C++11 起)</span></td></tr>
</table>
<p>若两个联合体成员均为标准布局类型，则在任何编译器上检验其公共子序列都是良好定义的。
</p>
<h4><span class="mw-headline" id=".E6.88.90.E5.91.98.E7.94.9F.E5.AD.98.E6.9C.9F">成员生存期</span></h4>
<p>联合体成员的<a href="lifetime.html" title="cpp/language/lifetime">生存期</a>始于该成员被设为活跃（active）时。若另一成员先前为活跃，则其生存期终止。
</p><p>当联合体的活跃成员通过形式为 <code>E1 = E2</code> 的复制表达式（使用内建赋值运算符或平凡的赋值运算符）所切换时，对于 <code>E1</code> 中的各个成员访问和数组下标子表达式中出现的，其类型并非拥有非平凡或弃置的默认构造函数的类的每个联合体成员 X，若 X 的修改在类型别名使用规则下会具有未定义行为，则在所指名的存储中隐式创建一个 X 类型的对象；不进行初始化，且其生存期的开始按顺序晚于其左右的操作数的值计算，而早于赋值。 
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">union</span> A <span class="br0">{</span> <span class="kw4">int</span> x<span class="sy4">;</span> <span class="kw4">int</span> y<span class="br0">[</span><span class="nu0">4</span><span class="br0">]</span><span class="sy4">;</span> <span class="br0">}</span><span class="sy4">;</span>
<span class="kw1">struct</span> B <span class="br0">{</span> A a<span class="sy4">;</span> <span class="br0">}</span><span class="sy4">;</span>
<span class="kw1">union</span> C <span class="br0">{</span> B b<span class="sy4">;</span> <span class="kw4">int</span> k<span class="sy4">;</span> <span class="br0">}</span><span class="sy4">;</span>
<span class="kw4">int</span> f<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span>
  C c<span class="sy4">;</span>               <span class="co1">// 不开始任何联合体成员的生存期</span>
  c.<span class="me1">b</span>.<span class="me1">a</span>.<span class="me1">y</span><span class="br0">[</span><span class="nu0">3</span><span class="br0">]</span> <span class="sy1">=</span> <span class="nu0">4</span><span class="sy4">;</span>    <span class="co1">// OK："c.b.a.y[3]" 指名联合体成员 c.b 与 c.b.a.y;</span>
                     <span class="co1">// 这创建对象以保有联合体成员 c.b 和 c.b.a.y</span>
  <span class="kw1">return</span> c.<span class="me1">b</span>.<span class="me1">a</span>.<span class="me1">y</span><span class="br0">[</span><span class="nu0">3</span><span class="br0">]</span><span class="sy4">;</span> <span class="co1">// OK：c.b.a.y 指代新创建的对象</span>
<span class="br0">}</span>
 
<span class="kw1">struct</span> X <span class="br0">{</span> <span class="kw4">const</span> <span class="kw4">int</span> a<span class="sy4">;</span> <span class="kw4">int</span> b<span class="sy4">;</span> <span class="br0">}</span><span class="sy4">;</span>
<span class="kw1">union</span> Y <span class="br0">{</span> X x<span class="sy4">;</span> <span class="kw4">int</span> k<span class="sy4">;</span> <span class="br0">}</span><span class="sy4">;</span>
<span class="kw4">void</span> g<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span>
  Y y <span class="sy1">=</span> <span class="br0">{</span> <span class="br0">{</span> <span class="nu0">1</span>, <span class="nu0">2</span> <span class="br0">}</span> <span class="br0">}</span><span class="sy4">;</span> <span class="co1">// OK，y.x 为活跃联合体成员 (9.2)</span>
  <span class="kw4">int</span> n <span class="sy1">=</span> y.<span class="me1">x</span>.<span class="me1">a</span><span class="sy4">;</span>
  y.<span class="me1">k</span> <span class="sy1">=</span> <span class="nu0">4</span><span class="sy4">;</span>   <span class="co1">// OK：结束 y.x 的生存期，y.k 是联合体的活跃成员</span>
  y.<span class="me1">x</span>.<span class="me1">b</span> <span class="sy1">=</span> n<span class="sy4">;</span> <span class="co1">// 未定义行为：y.x.b 在其生存期外被修改，</span>
             <span class="co1">// "y.x.b" 指名 y.x，但 X 的默认构造函数被弃置，</span>
             <span class="co1">// 故联合体成员 y.x 的生存期不会隐式开始</span>
<span class="br0">}</span></pre></div></div>
<h4><span class="mw-headline" id=".E5.8C.BF.E5.90.8D.E8.81.94.E5.90.88.E4.BD.93">匿名联合体</span></h4>
<p><i>匿名联合体</i>是不同时定义任何变量（包括联合体类型的对象、引用或指向联合体的指针）的无名的联合体定义。
</p>
<table class="t-sdsc-begin">

<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr>
<tr class="t-sdsc">
<td class="t-sdsc-nopad"> <code><b>union</b></code> <code><b>{ </b></code> <span class="t-spar">成员说明</span> <code><b>} </b></code> <code><b>;</b></code>
</td>
<td class="t-sdsc-nopad">
</td>
<td class="t-sdsc-nopad">
</td></tr>



<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr></table>
<p>匿名联合体有更多限制：它们不能有成员函数，不能有静态数据成员，且所有数据成员必须为公开。所允许的声明仅有非静态数据成员<span class="t-rev-inl t-since-cxx14"><span>和 <a href="static_assert.html" title="cpp/language/static assert">static_assert</a> 声明</span> <span><span class="t-mark-rev t-since-cxx14">(C++14 起)</span></span></span>。
</p><p>匿名联合体的成员被注入到其外围作用域中（而且必须不与其中声明的其他名字冲突）。
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw4">int</span> main<span class="br0">(</span><span class="br0">)</span>
<span class="br0">{</span>
    <span class="kw1">union</span>
    <span class="br0">{</span>
        <span class="kw4">int</span> a<span class="sy4">;</span>
        <span class="kw4">const</span> <span class="kw4">char</span><span class="sy2">*</span> p<span class="sy4">;</span>
    <span class="br0">}</span><span class="sy4">;</span>
    a <span class="sy1">=</span> <span class="nu0">1</span><span class="sy4">;</span>
    p <span class="sy1">=</span> <span class="st0">"Jennifer"</span><span class="sy4">;</span>
<span class="br0">}</span></pre></div></div>
<p>命名空间作用域的匿名联合体必须声明为 static，除非它们出现于无名命名空间。
</p>
<h4><span class="mw-headline" id=".E8.81.94.E5.90.88.E4.BD.93.E5.BC.8F.E7.9A.84.E7.B1.BB">联合体式的类</span></h4>
<p><i>联合体式的类（union-like class）</i>是至少拥有一个匿名联合体为其成员的（非联合）类，或者是联合体。联合体式的类拥有一组<i>变体成员（variant member）</i>：
</p>
<ul><li> 其成员匿名联合体的非静态数据成员；
</li><li> 另外，若联合体式的类是联合体，则为其并非匿名联合体的非静态数据成员。
</li></ul>
<p>联合体式的类可用于实现<a href="https://en.wikipedia.org/wiki/Tagged_union" class="extiw" title="enwiki:Tagged union">带标签联合体（tagged union）</a>。
</p>
<div class="t-example"><div class="t-example-live-link"><div class="coliru-btn coliru-btn-run-init">运行此代码</div></div>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="co2">#include &lt;iostream&gt;</span>
 
<span class="co1">// S 拥有一个非静态数据成员（tag），三个枚举项成员（CHAR、INT、DOUBLE），</span>
<span class="co1">// 和三个变体成员（c、i、d）</span>
<span class="kw1">struct</span> S
<span class="br0">{</span>
    <span class="kw2">enum</span><span class="br0">{</span>CHAR, INT, DOUBLE<span class="br0">}</span> tag<span class="sy4">;</span>
    <span class="kw1">union</span>
    <span class="br0">{</span>
        <span class="kw4">char</span> c<span class="sy4">;</span>
        <span class="kw4">int</span> i<span class="sy4">;</span>
        <span class="kw4">double</span> d<span class="sy4">;</span>
    <span class="br0">}</span><span class="sy4">;</span>
<span class="br0">}</span><span class="sy4">;</span>
 
<span class="kw4">void</span> print_s<span class="br0">(</span><span class="kw4">const</span> S<span class="sy3">&amp;</span> s<span class="br0">)</span>
<span class="br0">{</span>
    <span class="kw1">switch</span><span class="br0">(</span>s.<span class="me1">tag</span><span class="br0">)</span>
    <span class="br0">{</span>
        <span class="kw1">case</span> S<span class="sy4">::</span><span class="me2">CHAR</span><span class="sy4">:</span> <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> s.<span class="me1">c</span> <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span> <span class="kw1">break</span><span class="sy4">;</span>
        <span class="kw1">case</span> S<span class="sy4">::</span><span class="me2">INT</span><span class="sy4">:</span> <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> s.<span class="me1">i</span> <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span> <span class="kw1">break</span><span class="sy4">;</span>
        <span class="kw1">case</span> S<span class="sy4">::</span><span class="me2">DOUBLE</span><span class="sy4">:</span> <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> s.<span class="me1">d</span> <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span> <span class="kw1">break</span><span class="sy4">;</span>
    <span class="br0">}</span>
<span class="br0">}</span>
 
<span class="kw4">int</span> main<span class="br0">(</span><span class="br0">)</span>
<span class="br0">{</span>
    S s <span class="sy1">=</span> <span class="br0">{</span>S<span class="sy4">::</span><span class="me2">CHAR</span>, <span class="st0">'a'</span><span class="br0">}</span><span class="sy4">;</span>
    print_s<span class="br0">(</span>s<span class="br0">)</span><span class="sy4">;</span>
    s.<span class="me1">tag</span> <span class="sy1">=</span> S<span class="sy4">::</span><span class="me2">INT</span><span class="sy4">;</span>
    s.<span class="me1">i</span> <span class="sy1">=</span> <span class="nu0">123</span><span class="sy4">;</span>
    print_s<span class="br0">(</span>s<span class="br0">)</span><span class="sy4">;</span>
<span class="br0">}</span></pre></div></div>
<p>输出：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="text source-text"><pre class="de1">a
123</pre></div></div> 
</div>
 <table class="t-rev-begin">
<tr class="t-rev t-since-cxx17"><td>
<p>C++ 标准库包含 <span class="t-lc"><a href="../utility/variant.html" title="cpp/utility/variant">std::variant</a></span>，它可取代联合体和联合体式的类的大多数用途。上例可重写为
</p>
<div class="t-example"><div class="t-example-live-link"><div class="coliru-btn coliru-btn-run-init">运行此代码</div></div>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="co2">#include &lt;variant&gt;</span>
<span class="co2">#include &lt;iostream&gt;</span>
 
<span class="kw4">int</span> main<span class="br0">(</span><span class="br0">)</span>
<span class="br0">{</span>
    <a href="../utility/variant.html"><span class="kw1085">std::<span class="me2">variant</span></span></a><span class="sy1">&lt;</span><span class="kw4">char</span>, <span class="kw4">int</span>, <span class="kw4">double</span><span class="sy1">&gt;</span> s <span class="sy1">=</span> <span class="st0">'a'</span><span class="sy4">;</span>
    <a href="../utility/variant/visit.html"><span class="kw1086">std::<span class="me2">visit</span></span></a><span class="br0">(</span><span class="br0">[</span><span class="br0">]</span><span class="br0">(</span><span class="kw4">auto</span> x<span class="br0">)</span><span class="br0">{</span> <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> x <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span><span class="br0">}</span>, s<span class="br0">)</span><span class="sy4">;</span>
    s <span class="sy1">=</span> <span class="nu0">123</span><span class="sy4">;</span>
    <a href="../utility/variant/visit.html"><span class="kw1086">std::<span class="me2">visit</span></span></a><span class="br0">(</span><span class="br0">[</span><span class="br0">]</span><span class="br0">(</span><span class="kw4">auto</span> x<span class="br0">)</span><span class="br0">{</span> <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> x <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span><span class="br0">}</span>, s<span class="br0">)</span><span class="sy4">;</span>
<span class="br0">}</span></pre></div></div>
<p>输出：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="text source-text"><pre class="de1">a
123</pre></div></div> 
</div>
</td>
<td><span class="t-mark-rev t-since-cxx17">(C++17 起)</span></td></tr>
</table>
<h3><span class="mw-headline" id=".E7.BC.BA.E9.99.B7.E6.8A.A5.E5.91.8A">缺陷报告</span></h3>
<p>下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
</p>
<table class="dsctable" style="font-size:0.8em">
<tr>
<th> DR
</th>
<th> 应用于
</th>
<th> 出版时的行为
</th>
<th> 正确行为
</th></tr>
<tr>
<td> <a rel="nofollow" class="external text" href="https://wg21.cmeerw.net/cwg/issue1940">CWG 1940</a>
</td>
<td> C++14
</td>
<td> 匿名联合体仅允许非静态数据成员
</td>
<td> 亦允许 static_assert
</td></tr></table>
<h3><span class="mw-headline" id=".E5.8F.82.E9.98.85">参阅</span></h3>
<table class="t-dsc-begin">

</table>

<!-- 
NewPP limit report
Preprocessor visited node count: 2034/1000000
Preprocessor generated node count: 7100/1000000
Post‐expand include size: 54357/2097152 bytes
Template argument size: 18537/2097152 bytes
Highest expansion depth: 14/40
Expensive parser function count: 0/100
-->

<!-- Saved in parser cache with key mwiki1-mwiki_zh_:pcache:idhash:2764-0!*!0!!zh!*!zh!* and timestamp 20200223155729 -->
</div>                    <!-- /bodycontent -->
                                        <!-- printfooter -->
                    <div class="printfooter">
                    来自“<a href="https://zh.cppreference.com/mwiki/index.php?title=cpp/language/union&amp;oldid=60229">https://zh.cppreference.com/mwiki/index.php?title=cpp/language/union&amp;oldid=60229</a>”                    </div>
                    <!-- /printfooter -->
                                                            <!-- catlinks -->
                    <!-- /catlinks -->
                                                            <div class="visualClear"></div>
                    <!-- debughtml -->
                                        <!-- /debughtml -->
                </div>
                <!-- /bodyContent -->
            </div>
        </div>
        <!-- /content -->
        <!-- footer -->
        <div id="cpp-footer-base" class="noprint">
            <div id="footer">
                        <div id="cpp-navigation">
            <h5>导航</h5>
            <ul><li><a href="https://zh.cppreference.com/w/cpp/language/union">Online version</a></li><li>Offline version retrieved 2020-03-14 18:00.</li></ul></div>
                        <ul id="footer-info">
                                    <li id="footer-info-lastmod"> 本页面最后修改于2019年5月5日 (星期日) 04:17。</li>
                                    <li id="footer-info-viewcount">此页面已被浏览过26,563次。</li>
                            </ul>
                    </div>
        </div>
        <!-- /footer -->
        <script>if(window.mw){
mw.loader.state({"site":"loading","user":"missing","user.groups":"ready"});
}</script>
<script src="../../../common/skin_scripts.js"></script>
<script>if(window.mw){
mw.loader.load(["mediawiki.action.view.postEdit","mediawiki.user","mediawiki.page.ready","mediawiki.searchSuggest","mediawiki.hidpi","ext.gadget.MathJax","ext.gadget.ColiruCompiler"], null, true);
}</script>
<script src="../../../common/site_scripts.js"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-2828341-1']);
_gaq.push(['_setDomainName', 'cppreference.com']);
_gaq.push(['_trackPageview']);
</script><!-- Served in 0.922 secs. -->
	</body>
<!-- Cached 20200223155729 -->
</html>